package com.xinrui.service;

import com.xinrui.dao.UserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * 配置security的类实现UserDetailsService
 */
public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        调用dao层
        UserInfo userInfoDb = findByUsername(username);
//        初始角色所需要的角色和权限
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
//        添加一个角色:角色必须带ROLE_
        SimpleGrantedAuthority role_admin = new SimpleGrantedAuthority("ROLE_ADMIN");
        authorities.add(role_admin);
//        添加一个权限
        role_admin = new SimpleGrantedAuthority("add");
        authorities.add(role_admin);
        User securityUser = new User(username, userInfoDb.getPassword(), authorities);
        return securityUser;
    }

    //    模拟dao层数据
    private UserInfo findByUsername (String username){
        if("admin".equals(username)) {
            UserInfo user = new UserInfo();
            user.setUsername("admin");
            user.setPassword("{noop}1234");
            return user;
        }
        return null;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // encode加密
        System.out.println(encoder.encode("1234"));

        // 密码匹配:明文,密文
        System.out.println(encoder.matches("1234", "$2a$10$u/BcsUUqZNWUxdmDhbnoeeobJy6IBsL1Gn/S0dMxI2RbSgnMKJ.4a"));
    }
}
